<?php

namespace App\Console\Commands\Push;

use App\Library\FeiShu\SendFs;
use App\Library\Rms\KfosCurl;
use App\Library\Rms\RmsCurl;
use Illuminate\Console\Command;
use Kuafu\GeneralFs\BuildFs;
use Kuafu\GeneralFs\FsCardEstablish;
use KuafuComposer\ApiTime\Service\ApiTimeService;

class ApiTimeFsCardCommand extends Command
{
    protected $signature = 'push:api-time-fs-card {limit} {fsRobot} {startDate?} {endDate?}';

    protected $description = 'api使用情况统计，飞书卡片推送';

    private $fsRobot;

    public function handle()
    {
        $startDate = $this->argument('startDate');
        $endDate   = $this->argument('endDate');
        $limit     = (int)$this->argument('limit', 10);
        $this->fsRobot   = $this->argument('fsRobot');

        // 默认昨天
        if (!$startDate) {
            $startDate = date('Ymd', strtotime('-1 day'));
        }

        if (!$endDate) {
            $endDate = date('Ymd', strtotime('-1 day'));
        }

        // 统一格式化成Ymd
        $startDate = date('Ymd', strtotime($startDate));
        $endDate   = date('Ymd', strtotime($endDate));

        $enums = ['rms', 'tiger', 'kfos'];
        foreach ($enums as $appName) {

            switch ($appName) {
                case 'rms':
                    $lists = RmsCurl::getIns()->do('api/internal/apiTime/batchLists', ['startDate' => $startDate, 'endDate' => $endDate, 'limit' => $limit], 'GET')['data'] ?? [];
                    break;
                case 'kfos':
                    $lists = KfosCurl::getIns()->do('internal/apiTime/batchLists', ['startDate' => $startDate, 'endDate' => $endDate, 'limit' => $limit], 'GET')['data'] ?? [];
                    break;
                case 'tiger':
                    $lists = (new ApiTimeService('access'))
                        ->doListsBatch((int)$startDate, (int)$endDate, $limit)
                        ->getLists();
                    break;
            }

            $this->send($startDate, $endDate, $appName, $lists);

            sleep(1);
        }
    }

    private function send(string $startDate, string $endDate, string $appName, array $lists)
    {
        $fStartDate = date('Y.m.d', strtotime($startDate));
        $fEndDate   = date('Y.m.d', strtotime($endDate));

        $appEnv = config('app.env');

        $card = (new FsCardEstablish())
            ->setHeader('green', "{$fStartDate}-{$fEndDate} {$appName}.{$appEnv}接口调用情况");

        // table第一行
        $tr = [
            'tag'              => 'column_set',
            'flex_mode'        => 'none',
            'background_style' => 'grey',
            'columns'          => [],
        ];

        $header = ['调用次数', '平均耗时ms', '最大耗时ms', '>3秒次数', '>5秒次数', '>10秒次数'];
        foreach ($header as $item) {
            $tr['columns'][] = $this->td($item);
        }

        $card = $card->pushElements($tr);
        $card = $card->pushElements([
            'tag' => 'hr',
        ]);

        // table内容
        foreach ($lists as $k => $val) {
            $sort = $k + 1;

            $tr = [
                'tag'              => 'column_set',
                'flex_mode'        => 'none',
                'background_style' => 'grey',
                'columns'          => [],
            ];

            $card = $card->pushElements([
                'tag'     => 'markdown',
                'content' => "**{$sort}.{$val['uri']}**"
            ]);

            $tr['columns'][] = $this->td($this->number_f($val['request_num']));
            $tr['columns'][] = $this->td($this->number_f($val['avg_ms']));
            $tr['columns'][] = $this->td($this->number_f(($val['max_ms'])));
            $tr['columns'][] = $this->td($this->number_f($val['slow_num_3000']));
            $tr['columns'][] = $this->td($this->number_f($val['slow_num_5000']));
            $tr['columns'][] = $this->td($this->number_f(($val['slow_num_10000'])));

            $card = $card->pushElements($tr);
            $card = $card->pushElements([
                'tag' => 'hr',
            ]);
        }
        $card = $card->getTemplateArr();

        BuildFs::newRobot($this->fsRobot, BuildFs::MSG_TYPE_CARD)
               ->setCardContent($card)
               ->send();
    }

    private function number_f(int $number): string
    {
        return number_format($number);
    }

    private function td(string $item): array
    {
        return [
            'tag'            => 'column',
            'width'          => 'weighted',
            'weight'         => 1,
            'vertical_align' => 'top',
            'elements'       => [
                [
                    'tag'  => 'div',
                    'text' => [
                        'content' => $item,
                        'tag'     => 'plain_text',
                    ],
                ],
            ],
        ];
    }
}
